<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="505px" top="10vh" @close='close' class='ddosDialog'>
    <div class="dialogContentBoxMaxHeight80">
      <el-form ref="form" :model="record" label-width="105px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input v-emoji v-model="record.name" style="width:215px;" size='small' ref="recordName"></el-input>
        </el-form-item>
        <el-form-item :label="$t('IP类型')" prop="iptype">
          <el-radio-group v-model="record.iptype" :disabled='record.id !== ""' @change="ipTypeChange">
            <el-radio label="ipv4" class="ipv4">IPv4</el-radio>
            <el-radio label="ipv6" class="ipv6">IPv6</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('地址对象')" prop="addr">
          <el-select v-model="record.addr" ref="addr" size='small' filterable>
            <el-option v-for="item in addrList[record.iptype]" :key="item.name" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <el-button type="primary" plain size='small' style="margin-left:10px" @click="addAddrClick">{{$t('添加IP')}}</el-button>
        </el-form-item>
        <!-- <el-form-item :label="$t('地址对象')" prop="addr6" v-if="record.iptype === 'ipv6'">
          <el-select v-model="record.addr6" size='small' filterable>
            <el-option v-for="item in addr6List" :key="item.name" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <el-button type="primary" plain size='small' style="margin-left:10px" @click="addAddrClick">{{$t('添加IP')}}</el-button>
        </el-form-item> -->
        <el-form-item :label="$t('策略状态')" prop="status">
          <el-switch :width="lang === 'zh'?56:70" v-model="record.status" class="status switch" active-color="#009966" inactive-color="#CCCCCC" active-value="on" inactive-value="off" :active-text="$t('开启')" :inactive-text="$t('关闭')"></el-switch>
        </el-form-item>
        <el-form-item :label="$t('描述')" prop="desc">
          <el-input v-emoji type="textarea" @keydown.native="handleKeyCode($event)" :autosize="{ minRows: 2, maxRows: 4 }" v-model="record.desc" ref="desc" size='small'></el-input>
        </el-form-item>
      </el-form>
    </div>
    <AddrTools v-if="addrToolsDialog" ref="addrToolsDialogVisible" @addrArrayTools='addrArrayTools'></AddrTools>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addFlood, editFlood } from '@/api/safe/ddos'
import { getAddrArray } from '@/api/list/addr'
import AddrTools from './AddrTools'
import { inputClass, texttextClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'DdosDialog',
  components: {
    AddrTools
  },
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入策略名称')))
      } else if (value.length > 128) {
        callback(new Error(this.$t('输入内容不应超出长度 128 个字节')))
      } else {
        callback()
      }
    }
    var validateAddr = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      addrToolsDialog: false,
      record: {
        id: '',
        name: '',
        iptype: 'ipv4',
        addr: '',
        status: 'on', // on/off
        desc: ''
      },
      recordCopy: {
        id: '',
        name: '',
        iptype: 'ipv4',
        addr: '',
        status: 'on', // on/off
        desc: ''
      },
      addr4: '',
      addr6: '',
      addrList: {
        'ipv4': [],
        'ipv6': []
      },
      lang: this.$i18n.locale,
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        addr: [{ required: false, validator: validateAddr, trigger: 'change' }]
      }
    }
  },
  watch: {
    'record.addr': {
      handler (val) {
        if (this.record.iptype === 'ipv4') {
          this.addr4 = val
        } else if (this.record.iptype === 'ipv6') {
          this.addr6 = val
        }
      }
    },
    'record.desc': {
      handler (newVal) {
        this.record.desc = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.record = Object.assign(this.record, data)
      this.$nextTick(() => {
        const data = ['recordName']
        const textdata = ['desc']
        const selectData = ['addr']
        inputClass(this.$refs, data)
        texttextClass(this.$refs, textdata)
        selectClass(this.$refs, selectData)
      })
      // if (this.record.iptype === 'ipv4' && this.record.addr) {
      //   this.addr4 = this.record.addr
      // } else if (this.record.iptype === 'ipv6' && this.record.addr) {
      //   this.addr6 = this.record.addr
      // }
      getAddrArray().then(res => {
        if (res.status === 0) {
          let resList = res.info
          resList.splice(0, 1)
          for (let item of resList) {
            item.nameShow = this.$t('地址-') + item.name
            if (item.ip_type < 4) {
              this.addrList['ipv4'].push(item)
            } else if (item.ip_type < 6) {
              this.addrList['ipv6'].push(item)
            }
          }
          // if (!this.record.id) {
          //   if (this.record.iptype === 'ipv4' && this.addrList['ipv4'].length > 0) {
          //     this.record.addr = this.addrList['ipv4'][0].name
          //   } else if (this.record.iptype === 'ipv6' && this.addrList['ipv6'].length > 0) {
          //     this.record.addr = this.addrList['ipv6'][0].name
          //   }
          // }
        }
      })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.record.addr = this.record.iptype === 'ipv4' ? this.addr4 : this.addr6
          if (this.record.id) {
            editFlood(this.record).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('编辑成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          } else {
            addFlood(this.record).then(res => {
              if (res.status === 0) {
                this.$message({
                  message: this.$t('添加成功'),
                  type: 'success'
                })
                this.close()
                this.$parent.listData()
              }
            })
          }
        }
      })
    },
    addAddrClick () {
      this.addrToolsDialog = true
      this.$nextTick(() => {
        this.$refs.addrToolsDialogVisible.init()
      })
    },
    // 用于添加地址结束后更新地址列表
    addrArrayTools (name, ipType) {
      this.addrList = {
        'ipv4': [],
        'ipv6': []
      }
      if (this.record.iptype === ipType) {
        this.record.addr = name
      }
      getAddrArray().then(res => {
        if (res.status === 0) {
          let resList = res.info
          resList.splice(0, 1)
          for (let item of resList) {
            if (item.ip_type < 4) {
              this.addrList['ipv4'].push(item)
            } else if (item.ip_type < 6) {
              this.addrList['ipv6'].push(item)
            }
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.addrList = {
        'ipv4': [],
        'ipv6': []
      }
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    ipTypeChange (value) {
      if (this.record.iptype === 'ipv4' && this.addrList['ipv4'].length > 0) {
        this.record.addr = this.addr4 ? this.addr4 : this.addrList['ipv4'][0].name
      } else if (this.record.iptype === 'ipv6' && this.addrList['ipv6'].length > 0) {
        this.record.addr = this.addr6 ? this.addr6 : this.addrList['ipv6'][0].name
      } else {
        this.record.addr = ''
      }
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.ddosDialog {
  .ivu-switch-checked {
    border-color: #5fb878;
    background-color: #5fb878;
  }
}
</style>
